package client

import (
	"sync"
	"github.com/streadway/amqp"
	"strings"
)

type ClientManager struct {
	ch      *amqp.Channel
	clients *sync.Map
}

func NewClientManager(ch *amqp.Channel) *ClientManager {
	return &ClientManager{
		ch:      ch,
		clients: new(sync.Map),
	}
}

func(manager *ClientManager) RegisterClient(compKeys string, qs []*amqp.Queue) error{
	_,exist := manager.clients.Load(compKeys)
	if exist {
		return NewRegisterError(1, "Client Duplicate registered.")
	}
	keys := strings.Split(compKeys, ".")
	newClient := NewClient(keys, qs, manager.ch)
	manager.clients.Store(compKeys, newClient)
	return nil
}

func(manager *ClientManager) GetClient(routingKeys []string) *Client{
	compKey := compositeKeys(routingKeys)
	client,exist := manager.clients.Load(compKey)
	if exist {
		return client.(*Client)
	}else{
		return nil
	}
}

func compositeKeys(routingKeys []string) string {
	var compKey string
	for i,key := range routingKeys {
		if i == len(routingKeys)-1 {
			compKey += key
		} else {
			compKey += (key + ".")
		}
	}
	return compKey
}
